<?php
/**
 * Descript:
 * User: lufeng501206@gmail.com
 * Date: 2017/3/12 13:51
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Models\ExtractCash;
use App\Models\Home\User;
use App\Repositories\TasksRepos;
use App\Repositories\UsersRepos;
use App\Models\Admin\Tasks;
use App\Models\Home\Orders;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    private $tasksRepos = null;
    private $usersRepos = null;

    public function __construct(UsersRepos $usersRepos, TasksRepos $tasksRepos)
    {
        $this->usersRepos = $usersRepos;
        $this->tasksRepos = $tasksRepos;
        $this->middleware('verify.auth', ['except' => 'index']);
    }

    /**
     * 获取任务列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function index(Request $request)
    {
        $conditions = $inputs = $request->input();
        $conditions['state'] = 3; //发布中
        $conditions['begin_time'] = date('Y-m-d H:i:s',time());
        $lists = $this->tasksRepos->getTasksLists($conditions);
        return successJson($lists);
    }

    /**
     * 获取任务详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getTaskInfo($id)
    {
        $userid = $this->usersRepos->getLoginUserId();
        $data = $this->tasksRepos->getTaskInfo($id);
        $data['login_user_state'] = $this->tasksRepos->getUserTaskDetail($id,$userid);
        $data['finish_lists'] = $this->tasksRepos->getFinishOrder($id);
        $data['user_finish_data'] = $this->tasksRepos->getUserFinishData($id,$userid);
        $taskModel = Tasks::FindOrFail($id);
        $data['used_nums'] = $taskModel->orders->count();
        return successJson($data);
    }

    /**
     * 领取任务
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getTask(Request $request, $id)
    {
        $inputs = $request->input();
        $userid = $this->usersRepos->getLoginUserId();
        //判断是否领取过
        $exitOrderModel = Orders::where('task_id', $id)
            ->where('user_id', $userid)
            ->first();
        if (empty($exitOrderModel)) {
            $taskModel = Tasks::FindOrFail($id);
            $usedNums = $taskModel->orders->count();
            if ($taskModel->number <= $usedNums) {
                return errorJson([], '任务已经被领完了');
            }
            $orderModel = new Orders();
            $orderModel->task_id = $id;
            $orderModel->user_id = $userid;
            $orderModel->state = 1; //审批状态
            $res = $orderModel->save();
            if ($res) {
                //触发消息
                $taskDetails = $this->tasksRepos->getTaskInfo($id);
                $msgData['${mission_name}'] = $taskDetails['title'];
                $msgData['${mission_id}'] = $taskDetails['id'];
                $this->usersRepos->triggerMessage($userid,'任务领取',$msgData);
                return successJson([], '领取任务成功');
            } else {
                return errorJson([], '领取任务失败');
            }
        } else {
            return errorJson([], '任务已经领取过了');
        }
    }

    /**
     * 上传任务图片接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function uploadTaskImages(Request $request)
    {
        $files = $request->file();
        if (!empty($files)) {
            foreach ($files as $file) {
                $relatedPath = 'tasks/' . date('Y-m-d') . "/" . session('login_user');
                $path[] = $file->store($relatedPath);
            }
            return successJson($path);
        } else {
            return errorJson();
        }
    }

    /**
     * 完成提交任务
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function finishTask(Request $request, $id)
    {
        $data = $inputs = $request->input();
        // 判断任务是否过期
        $taskDetails = $this->tasksRepos->getTaskInfo($id);
        if(time() >= strtotime($taskDetails['deadlime'])){
            return errorJson([], '任务已经过了截止时间');
        }
        $userId = $this->usersRepos->getLoginUserId();
        $orderModel = Orders::where('task_id', $id)->where('user_id', $userId)->first();
        $orderModel->images = $data['images'];
        $orderModel->mobile = $data['mobile'];
        // 提交时间
        $orderModel->finish_time = date('Y-m-d H:i:s',time());
        $orderModel->state = 2; //结束状态
        $res = $orderModel->save();
        if ($res) {
            //触发消息
            $msgData['${mission_name}'] = $taskDetails['title'];
            $msgData['${mission_id}'] = $taskDetails['id'];
            $this->usersRepos->triggerMessage($userId,'任务提交',$msgData);
            return successJson([], '任务提交成功');
        } else {
            return errorJson([], '任务提交失败');
        }
    }

    /**
     * 用户任务列表
     * @param \Request $request
     */
    public function getUserTaskLists(Request $request)
    {
        $conditions = $inputs = $request->input();
        $userId = $this->usersRepos->getLoginUserId();
        $lists = $this->tasksRepos->getTasksListsByUserId($userId, $conditions);
        return successJson($lists);
    }

    /**
     * 提现申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function applyExtractCash(Request $request)
    {
        $data = $input = $request->input();
        $userId = $this->usersRepos->getLoginUserId();
        //事务操作
        \DB::beginTransaction();
        $userModel = User::FindOrFail($userId);
        $userModel->balance -= $data['cash_money'];
        if ($userModel->balance < 0) {
            \DB::rollBack();
            return errorJson('', '余额不足');
        }
        $res = $userModel->save();
        if (empty($res)) {
            \DB::rollBack();
            return errorJson('', '提现失败');
        }
        $cashModel = new ExtractCash();
        $data['user_id'] = $userId;
        $res = $cashModel->create($data);
        if (empty($res)) {
            \DB::rollBack();
            return errorJson('', '提现失败');
        }
        //事务提交
        //触发消息
        $msgData['${cash_id}'] = $res->id;
        $this->usersRepos->triggerMessage($userId,'提现申请',$msgData);
        \DB::commit();
        return successJson('', '申请已提交，请等待后台审核');
    }

    /**
     * 获取提现记录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getApplyExtractCashRecord(Request $request)
    {
        $inputs = $request->input();
        $type = $inputs['type'];
        $userId = $this->usersRepos->getLoginUserId();
        if ($type == 1) {
            $extractCashModel = ExtractCash::select('*',\DB::raw('DATE_FORMAT(created_at,\'%Y-%m\') as month'));
            $extractCashModel = $extractCashModel->whereIn('extract_state',['1','2']);
            $extractCashModel = $extractCashModel->where('user_id',$userId);
            $lists = $extractCashModel->get()->toArray();
            $returnList = [];
            if (!empty($lists)) {
                foreach ($lists as $key => $value) {
                    if (empty($returnList[$value['month']])) {
                        $returnList[$value['month']] = [];
                    }
                    $returnList[$value['month']][] = $value;
                }
            }
            $data['lists'] = $returnList;
            return successJson($data);
        } elseif ($type == 2) {
            // 获取结算列表
            $userid = $this->usersRepos->getLoginUserId();
            $conditions['state'] = 4;
            // 获取完成任务
            $userTaskLists = $this->tasksRepos->getTasksListsByUserId($userid,$conditions);
            // 获取提成任务
            $recommendUserTaskLists = [];
            // 获取好友列表
            $userInfo = $this->usersRepos->getUserInfo($userid);
            $recommendUserLists = $this->usersRepos->getRecommendUserLists($userInfo['account']);
            if (!empty($recommendUserLists) && is_array($recommendUserLists)) {
                foreach ($recommendUserLists as $key => $value) {
                    $lists = $this->tasksRepos->getTasksListsByUserId($value['id'],$conditions);
                    $recommendUserTaskLists = array_merge($recommendUserTaskLists,$lists);
                }
            }
            // 汇总数据
            $allTaskLists = array_merge($userTaskLists,$recommendUserTaskLists);
            // 返回数据
            $returnData = [];
            if (!empty($allTaskLists) && is_array($allTaskLists)) {
                foreach ($allTaskLists as $key => $value) {
                    $temp = [];
                    $month = date("Y-m",strtotime($value['updated_at']));
                    if ($value['user_id'] == $userid) {
                        $temp['money'] = $value['money'];
                    } else {
                        $temp['money'] = $value['rebate'];
                    }
                    if (empty($returnData[$month])) {
                        $returnData[$month] = [];
                        $returnData[$month]['total_nums'] = 0;
                        $returnData[$month]['total_cash_money'] = 0;
                    }
                    $returnData[$month]['month'] = $month ;
                    $returnData[$month]['total_nums'] ++ ;
                    $returnData[$month]['total_cash_money'] += $temp['money'];
                }
            }
            $lists = $returnData;
            ksort($lists);
//            $extractCashModel = ExtractCash::select(\DB::raw('count(1) as total_nums'),\DB::raw('sum(cash_money) as total_cash_money'), \DB::raw('DATE_FORMAT(updated_at,\'%Y-%m\') as month'));
//            $extractCashModel = $extractCashModel->whereIn('extract_state',['2']);
//            $extractCashModel = $extractCashModel->where('user_id',$userId);
//            $lists = $extractCashModel->groupBy('month')->get()->toArray();
        } else {
            $lists = [];
        }
        $data['lists'] = $lists;
        return successJson($data);
    }

    public function getTaskMoneyDetail(Request $request)
    {
        $month = $request->input('month');
        $userid = $this->usersRepos->getLoginUserId();
        $conditions['month'] = $month;
        $conditions['state'] = 4;
        // 获取完成任务
        $userTaskLists = $this->tasksRepos->getTasksListsByUserId($userid,$conditions);
        // 获取提成任务
        $recommendUserTaskLists = [];
        // 获取好友列表
        $userInfo = $this->usersRepos->getUserInfo($userid);
        $recommendUserLists = $this->usersRepos->getRecommendUserLists($userInfo['account']);
        if (!empty($recommendUserLists) && is_array($recommendUserLists)) {
            foreach ($recommendUserLists as $key => $value) {
                $lists = $this->tasksRepos->getTasksListsByUserId($value['id'],$conditions);
                $recommendUserTaskLists = array_merge($recommendUserTaskLists,$lists);
            }
        }
        // 汇总数据
        $allTaskLists = array_merge($userTaskLists,$recommendUserTaskLists);
        // 返回数据
        $returnData = [];
        if (!empty($allTaskLists) && is_array($allTaskLists)) {
            foreach ($allTaskLists as $key => $value) {
                $temp = [];
                $temp['title'] = $value['title'];
                $temp['time'] = $value['updated_at'];
                $temp['timestamp'] = strtotime($value['updated_at']);
                $temp['username'] = $value['name'];
                if ($value['user_id'] == $userid) {
                    $temp['type_name'] = "任务获得";
                    $temp['money'] = $value['money'];
                } else {
                    $temp['type_name'] = "推荐奖励";
                    $temp['money'] = $value['rebate'];
                }
                $returnData[] = $temp;
            }
        }
        if (!empty($returnData)) {
            $sort = array_column($returnData, 'timestamp');
            array_multisort($sort, SORT_ASC, $returnData);
        }
        return successJson($returnData);
    }

}